package com.estore.db.actions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.estore.db.beans.CategoryBean;
import com.estore.db.util.DBUtil;

public class CategoryActions extends DispatchAction {
	
	public ActionForward viewCategories(ActionMapping mapping,
							            ActionForm form,
							            HttpServletRequest request,
							            HttpServletResponse response){
		List<CategoryBean> catList = new ArrayList<CategoryBean>();
		String query = "Select * FROM estore.category_master order by cat_level";
		
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		
		try {
			con = DBUtil.getConnection();
			st = con.createStatement();
			rs = st.executeQuery(query);
			
			while(rs.next()){
				CategoryBean catBean = new CategoryBean();
				catBean.setID(rs.getInt(1));
				catBean.setCatLevel(rs.getInt(2));
				catBean.setCatLevelName(rs.getString(3));
				catBean.setDescription(rs.getString(4));
				catBean.setHtmlDescription(rs.getString(5));
				catList.add(catBean);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try{
				if (rs != null)
					rs.close();
				if (st != null)
					st.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		request.setAttribute("categories", catList);
		return mapping.findForward("SUCCESS");
	 }
}